package com.czxy.Demo23;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
        List<Animal> show = show();    // 调用方法 接收到一个数组
        //  遍历数组
        for (Animal animal : show) {
            System.out.println(animal);
        }
    }
    public static List<Animal> show() throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        //  创建一个父类集合  用于存放两个子类
        List<Animal> animals = new ArrayList<>();

        //  读取文件
        List<String> list = FileUtils.readLines(new File("dataAnimal.txt"), "UTF-8");

        for (String s : list) {
            String[] split = s.split(" ");
            String id = split[1].split("=")[1];     // 截取id
            String name = split[2].split("=")[1];   // 截取name
            String ac = split[3].split("=")[1];     // 截取 color / age

            //  通过截取的地址 反射创建对象
            Class<?> aClass = Class.forName(split[0]);
            Object o = aClass.newInstance();

            //  多态判断 并 创建对象添加到集合
            if (o instanceof Cat){
                animals.add(new Cat(id , name , ac));
            }
            if (o instanceof Dog){
                animals.add(new Dog(id , name , Integer.parseInt(ac)));
            }
        }
        return animals;
    }
}